/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.optimizer.index;

import org.apache.calcite.plan.RelOptCost;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dylan
 */
public class Configuration {

    private Set<CandidateIndex> candidateIndexSet;

    private RelOptCost afterCost;

    private Map<String, Set<String>> broadcastTable;

    public Configuration(Set<CandidateIndex> candidateIndexSet, RelOptCost afterCost,
                         Map<String, Set<String>> broadcastTable) {
        this.candidateIndexSet = candidateIndexSet;
        this.afterCost = afterCost;
        this.broadcastTable = broadcastTable;
    }

    public Configuration(Set<CandidateIndex> candidateIndexSet, RelOptCost afterCost) {
        this.candidateIndexSet = candidateIndexSet;
        this.afterCost = afterCost;
        this.broadcastTable = new HashMap<>();
    }

    public Set<CandidateIndex> getCandidateIndexSet() {
        return candidateIndexSet;
    }

    public RelOptCost getAfterCost() {
        return afterCost;
    }

    public void setAfterCost(RelOptCost afterCost) {
        this.afterCost = afterCost;
    }

    public Map<String, Set<String>> getBroadcastTable() {
        return broadcastTable;
    }

    public String broadcastSql() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Set<String>> entry : broadcastTable.entrySet()) {
            String schema = entry.getKey();
            for (String table : entry.getValue()) {
                sb.append("ALTER TABLE ").append(schema).append(".").append(table).append(" BROADCAST; ");
            }
        }
        return sb.toString();
    }

    public int totalIndexLength() {
        return getCandidateIndexSet().stream()
            .map(x -> x.getColumnNames().size()).reduce(0, (a, b) -> a + b).intValue();
    }
}
